#!/usr/bin/env python2.7
# -*-encoding:utf8-*-

import setting,os,time,sys
from DBSql import IQConnect
from preparation import *
import fun_apriori

reload(sys)
sys.setdefaultencoding('utf8')


pre = Preparation()

#generate srcfile.
pre.data_preparation(setting.SRCDATA_FILE_PATH)

#get city list and area_dic.
returned_list = pre.get_city_list()

#get area set.
area_set =  [str(i) for i in returned_list['area_dic'].keys()]

#time string.
date_str = time.strftime('%Y/%m/%d %H:%M:00',time.localtime(time.time()))
#checkpoint: returned_list['area_dic']
#checkpoint: area_set

#city list.
citys = returned_list['citys']

#setgroup_by_city list structure: {city1:{mdn1:(area_set,...),...},{city2..},...}
setgroup_by_city = pre.final_set(setting.SRCDATA_FILE_PATH,area_set)

#open file for writing rules.
write_rules = open(setting.RULE_FILE_PATH,'w')

#run apriori group by city.
for city_id in setgroup_by_city.keys():
    """
    list(setgroup_by_city[city_id].itervalues()) //[mdn1:(area1,area2..),...]
    list(setgroup_by_city[city_id].iterkeys())   //citys.
    """
    str_to_write = fun_apriori.fun_apriori(setgroup_by_city[city_id],returned_list['area_dic'],date_str,city_id)
    # write rules.
    write_rules.write(str_to_write.decode('utf8').encode('GBK'))
write_rules.close()

#load table.
load_sql = pre.load_rules()

